package com.yzz.shopping.utils

import android.view.View
import androidx.recyclerview.widget.RecyclerView
import com.yzz.shopping.ui.fragment.ShoppingFragment
import com.yzz.shopping.ui.widget.BackToTopView
import java.lang.Exception

/**
 * @Author : yangzuozhe
 * @Time : On 2022/3/7 14:54
 *
 * @Description : BackToTopUtils
 */
class BackToTopUtils {
    companion object {
        val instance = SingletonHolder.holder
    }

    private object SingletonHolder {
        val holder = BackToTopUtils()
    }

    fun initBackToTop(
        isNested: Boolean,
        recyclerView: RecyclerView?,
        backToTopView: BackToTopView?
    ) {
        if (!isNested) {
            initBackToTopClick(recyclerView, backToTopView)
            recyclerView?.addOnScrollListener(object : RecyclerView.OnScrollListener() {
                override fun onScrollStateChanged(
                    recyclerView: RecyclerView,
                    newState: Int
                ) {
                    super.onScrollStateChanged(recyclerView, newState)
                    if (!recyclerView.canScrollVertically(-1)) {
                        // 到达顶部
                        backToTopView?.visibility = View.GONE
                    } else {
                        // 没有到达顶部
                        backToTopView?.visibility = View.VISIBLE
                    }
                }
            })
        }
    }

    private fun initBackToTopClick(recyclerView: RecyclerView?, backToTopView: BackToTopView?) {
        backToTopView?.setOnClickListener {
            try {
                recyclerView?.scrollToPosition(0)
                backToTopView?.visibility = View.GONE
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }

}